from rest_framework import serializers  # 序列化器
from .models import *       # 导入所有模型类

# 定义序列化器
# 模型类名 + Serializer
# class StudentSerializer(serializers.Serializer):    # 序列化器类
#     id = serializers.CharField(label='ID', read_only=True)    # 只读
#     name = serializers.CharField(max_length=30, label='姓名')
#     age = serializers.IntegerField(label='年龄', required=False)
#     sex = serializers.IntegerField(label='性别', required=False)
#     create_time = serializers.DateTimeField(label='创建时间', required=False)
#     update_time = serializers.DateTimeField(label='更新时间', required=False)
#     is_delete = serializers.BooleanField(default=False, label='逻辑删除', required=False)
#
#     def create(self, validated_data):   # 字典 {‘name’：‘gy’, age: 18}  拆包==> name=gy,age=18
#         return Student.objects.create(**validated_data)
#
#     def update(self, instance, validated_data):
#         instance.name = validated_data.get('name', instance.name)
#         instance.age = validated_data.get('age', instance.age)
#         instance.sex = validated_data.get('sex', instance.sex)
#         instance.save()
#         return instance


class StudentSerializer(serializers.ModelSerializer):    # 序列化器类
    class Meta:
        model = Student     # 转序列化器
        # fields = '__all__'  # 映射展示所有字段
        exclude = ['is_delete'] # 不想展示的字段

        # 数据校验 数值范围
        extra_kwargs = {
            'age': {'min_value': 0, 'max_value': 100}
        }


    # 对象级别校验
    def validate(self, data):   # data 字典
        if 'mq' not in data['name'].lower():
            raise serializers.ValidationError('用户名需要包含mq字符')
        if data['age'] < 18:
            raise serializers.ValidationError('未成年不可访问')

        return data